package pl.vanta.mjuzik2.impl.formats;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;

import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.OrFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;

import pl.vanta.mjuzik2.api.FileInfo;
import pl.vanta.mjuzik2.api.FileFormat;
import pl.vanta.mjuzik2.api.services.FormatService;
import pl.vanta.utils.gui.filters.GuiFileFilter;

import com.google.inject.Inject;

public class FormatServiceImpl implements FormatService
{
	private final List<FileFormat>	formats;

	@Inject
	public FormatServiceImpl(List<FileFormat> formats)
	{
		this.formats = formats;
	}

	@Override
	public AudioFileFormat getAudioFileFormat(File file)
	{
		try
		{
			return AudioSystem.getAudioFileFormat(file);
		}
		catch (UnsupportedAudioFileException e)
		{
		}
		catch (IOException e)
		{
		}

		return null;
	}

	@Override
	public FileInfo getFileInfo(File file)
	{
		for (FileFormat format : this.formats)
		{
			AudioFileFormat aff = getAudioFileFormat(file);

			if (aff != null)
			{
				FileInfo fileInfo = format.getFileInfo(aff);

				if (fileInfo != null)
				{
					return fileInfo;
				}
			}
		}

		return null;
	}

	public List<FileFormat> getFormats()
	{
		return Collections.unmodifiableList(this.formats);
	}

	public List<String> getSupportedMusicFilesExtensions()
	{
		List<String> extensions = new ArrayList<String>();

		for (FileFormat info : this.formats)
		{
			extensions.addAll(Arrays.asList(info.getExtensions()));
		}

		return extensions;
	}

	public GuiFileFilter getMusicFilesFilter()
	{
		SuffixFileFilter sff = new SuffixFileFilter(getSupportedMusicFilesExtensions(), IOCase.INSENSITIVE);
		IOFileFilter dff = DirectoryFileFilter.DIRECTORY;

		GuiFileFilter gff = new GuiFileFilter(new OrFileFilter(sff, dff), "Music files");

		return gff;
	}
}